/*
 * @Author: yuki
 * @Date: 2025-11-06 10:00:00
 * @LastEditTime: 2025-11-05 20:32:40
 * @Description: 全局异常过滤器，统一处理所有异常响应
 */
import type { Response as ResponseFormat } from '@horoscope/shared';
import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  HttpException,
  HttpStatus
} from '@nestjs/common';
import type { Response } from 'express';

@Catch()
export class GlobalExceptionFilter<T extends Error>
  implements ExceptionFilter<T>
{
  catch(exception: T, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();

    // 默认状态码和错误信息
    let status = HttpStatus.INTERNAL_SERVER_ERROR;
    let message = '服务器内部错误';
    let errorData: Record<string, any> | null = null;

    // 处理HTTP异常
    if (exception instanceof HttpException) {
      status = exception.getStatus();

      // 获取异常响应体
      const exceptionResponse = exception.getResponse();

      // 处理NestJS的标准HTTP异常响应格式
      if (typeof exceptionResponse === 'object') {
        // 检查是否有message字段
        if ('message' in exceptionResponse) {
          message = exceptionResponse.message as string;
        }
        // 保留原始错误数据
        errorData = exceptionResponse;
      } else {
        message = exceptionResponse;
      }
    } else if (exception instanceof Error) {
      // 处理JavaScript原生错误
      message = exception.message || message;
      // 开发环境下显示堆栈信息，生产环境隐藏
      if (process.env.NODE_ENV === 'development') {
        errorData = {
          stack: exception.stack,
          name: exception.name
        };
      }
    }

    // 构建统一的响应格式
    const formattedResponse: ResponseFormat<any> = {
      code: status,
      message: message,
      data: errorData,
      success: false
    };

    // 发送响应
    response.status(status).json(formattedResponse);
  }
}
